<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>交易图表 - 事件合约交易平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .container {
            max-width: 100%;
            margin: 0;
            background: white;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 15px 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .header-left .logo {
            font-size: 1.8em;
        }
        
        .header-left h1 {
            font-size: 1.4em;
            font-weight: 700;
        }
        
        .nav-buttons {
            display: flex;
            gap: 10px;
        }
        
        .nav-btn {
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            font-size: 0.9em;
        }
        
        .nav-btn:hover {
            background: rgba(255,255,255,0.3);
            transform: translateY(-1px);
        }
        
        .chart-controls {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        .control-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .control-group label {
            font-weight: 500;
            color: #495057;
            font-size: 0.9em;
        }
        
        .control-select {
            padding: 6px 12px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 0.9em;
            background: white;
            cursor: pointer;
        }
        
        .control-select:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 2px rgba(79, 172, 254, 0.2);
        }
        
        .connection-status {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-left: auto;
        }
        
        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #dc3545;
        }
        
        .status-indicator.connected {
            background: #28a745;
        }
        
        .status-text {
            font-size: 0.85em;
            color: #6c757d;
        }
        
        .chart-container {
            flex: 1;
            position: relative;
            min-height: 800px;
            height: calc(100vh - 300px);
            background: white;
        }
        
        #tradingview_chart {
            width: 100%;
            height: 100%;
            min-height: 800px;
        }
        
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #4facfe;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        .loading-text {
            margin-top: 15px;
            color: #495057;
            font-size: 0.9em;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 12px 20px;
            border-left: 4px solid #dc3545;
            margin: 20px;
            border-radius: 4px;
            display: none;
        }
        
        .price-ticker {
            background: white;
            padding: 10px 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            gap: 30px;
        }
        
        .price-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 2px;
        }
        
        .price-label {
            font-size: 0.8em;
            color: #6c757d;
            font-weight: 500;
        }
        
        .price-value {
            font-size: 1.1em;
            font-weight: 600;
            color: #495057;
        }
        
        .price-change {
            font-size: 0.85em;
            font-weight: 500;
        }
        
        .price-change.positive {
            color: #28a745;
        }
        
        .price-change.negative {
            color: #dc3545;
        }
        
        @media (max-width: 768px) {
            .chart-controls {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .connection-status {
                margin-left: 0;
                margin-top: 10px;
            }
            
            .price-ticker {
                flex-wrap: wrap;
                gap: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部导航 -->
        <div class="header">
            <div class="header-left">
                <span class="logo">📈</span>
                <h1>交易图表</h1>
            </div>
            <div class="nav-buttons">
                <a href="index.html" class="nav-btn">🏠 主页</a>
                <a href="#" class="nav-btn" onclick="toggleFullscreen()">⛶ 全屏</a>
            </div>
        </div>
        
        <!-- 价格快显 -->
        <div class="price-ticker">
            <div class="price-item">
                <div class="price-label">当前价格</div>
                <div class="price-value" id="current-price">--</div>
            </div>
            <div class="price-item">
                <div class="price-label">24h变化</div>
                <div class="price-change" id="price-change">--</div>
            </div>
            <div class="price-item">
                <div class="price-label">24h高</div>
                <div class="price-value" id="price-high">--</div>
            </div>
            <div class="price-item">
                <div class="price-label">24h低</div>
                <div class="price-value" id="price-low">--</div>
            </div>
        </div>
        
        <!-- 图表控制 -->
        <div class="chart-controls">
            <div class="control-group">
                <label for="symbol-select">交易对:</label>
                <select id="symbol-select" class="control-select">
                    <option value="ETHUSDT">ETH/USDT</option>
                    <option value="BTCUSDT">BTC/USDT</option>
                </select>
            </div>
            
            <div class="control-group">
                <label for="interval-select">时间周期:</label>
                <select id="interval-select" class="control-select">
                    <option value="1m">1分钟</option>
                    <option value="5m">5分钟</option>
                    <option value="15m">15分钟</option>
                    <option value="1h" selected>1小时</option>
                    <option value="4h">4小时</option>
                    <option value="1d">1天</option>
                </select>
            </div>
            
            <div class="connection-status">
                <div class="status-indicator" id="status-indicator"></div>
                <span class="status-text" id="status-text">连接中...</span>
            </div>
        </div>
        
        <!-- 错误消息 -->
        <div class="error-message" id="error-message"></div>
        
        <!-- 图表容器 -->
        <div class="chart-container">
            <div id="tradingview_chart"></div>
            <div class="loading-overlay" id="loading-overlay">
                <div class="loading-spinner"></div>
                <div class="loading-text">正在加载图表数据...</div>
            </div>
        </div>
    </div>

    <!-- TradingView Charting Library -->
    <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
    
    <script>
        // 全局变量
        let widget = null;
        let websocket = null;
        let currentSymbol = 'ETHUSDT';
        let currentInterval = '1h';
        let isConnected = false;
        
        // DOM元素
        const symbolSelect = document.getElementById('symbol-select');
        const intervalSelect = document.getElementById('interval-select');
        const statusIndicator = document.getElementById('status-indicator');
        const statusText = document.getElementById('status-text');
        const errorMessage = document.getElementById('error-message');
        const loadingOverlay = document.getElementById('loading-overlay');
        const currentPrice = document.getElementById('current-price');
        const priceChange = document.getElementById('price-change');
        const priceHigh = document.getElementById('price-high');
        const priceLow = document.getElementById('price-low');
        
        // 自定义数据源
        const customDatafeed = {
            onReady: (callback) => {
                console.log('[onReady]: Method call');
                setTimeout(() => callback({
                    supported_resolutions: ['1', '5', '15', '60', '240', '1D'],
                    supports_marks: false,
                    supports_timescale_marks: false,
                    supports_time: true,
                }), 0);
            },
            
            searchSymbols: (userInput, exchange, symbolType, onResultReadyCallback) => {
                console.log('[searchSymbols]: Method call');
                onResultReadyCallback([]);
            },
            
            resolveSymbol: (symbolName, onSymbolResolvedCallback, onResolveErrorCallback) => {
                console.log('[resolveSymbol]: Method call', symbolName);
                
                const symbolInfo = {
                    name: symbolName,
                    description: symbolName,
                    type: 'crypto',
                    session: '24x7',
                    timezone: 'Asia/Shanghai',
                    ticker: symbolName,
                    exchange: 'Binance',
                    minmov: 1,
                    pricescale: 100,
                    has_intraday: true,
                    intraday_multipliers: ['1', '5', '15', '60', '240'],
                    supported_resolutions: ['1', '5', '15', '60', '240', '1D'],
                    volume_precision: 8,
                    data_status: 'streaming',
                };
                
                setTimeout(() => onSymbolResolvedCallback(symbolInfo), 0);
            },
            
            getBars: (symbolInfo, resolution, from, to, onHistoryCallback, onErrorCallback, firstDataRequest) => {
                console.log('[getBars]: Method call', symbolInfo, resolution, from, to);
                
                // 将TradingView分辨率转换为我们的间隔格式
                const intervalMap = {
                    '1': '1m',
                    '5': '5m', 
                    '15': '15m',
                    '60': '1h',
                    '240': '4h',
                    '1D': '1d'
                };
                
                const interval = intervalMap[resolution] || '1h';
                
                // 获取历史K线数据
                fetchKlineData(symbolInfo.name, interval, from * 1000, to * 1000)
                    .then(data => {
                        if (data && data.length > 0) {
                            const bars = data.map(item => ({
                                time: Math.floor(item.time / 1000) * 1000, // 确保是毫秒时间戳
                                low: item.low,
                                high: item.high,
                                open: item.open,
                                close: item.close,
                                volume: item.volume || 0
                            }));
                            
                            console.log('[getBars]: 返回数据', bars.length, '条');
                            onHistoryCallback(bars, { noData: false });
                        } else {
                            console.log('[getBars]: 无数据');
                            onHistoryCallback([], { noData: true });
                        }
                    })
                    .catch(error => {
                        console.error('[getBars]: 获取数据失败', error);
                        onErrorCallback(error);
                    });
            },
            
            subscribeBars: (symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) => {
                console.log('[subscribeBars]: Method call with subscriberUID:', subscriberUID);
                // 实时数据将通过WebSocket处理
            },
            
            unsubscribeBars: (subscriberUID) => {
                console.log('[unsubscribeBars]: Method call with subscriberUID:', subscriberUID);
            },
        };
        
        // 获取K线历史数据
        async function fetchKlineData(symbol, interval, startTime, endTime) {
            try {
                const limit = 1000;
                const url = `http://localhost:8769/api/klines/${symbol}?interval=${interval}&limit=${limit}`;
                
                console.log('获取K线数据:', url);
                
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.success && result.data) {
                    return result.data;
                } else {
                    console.warn('API返回错误:', result);
                    return [];
                }
            } catch (error) {
                console.error('获取K线数据失败:', error);
                // 返回模拟数据作为后备方案
                return generateMockData(symbol, interval);
            }
        }
        
        // 生成模拟K线数据
        function generateMockData(symbol, interval) {
            const now = Date.now();
            const data = [];
            const basePrice = symbol === 'ETHUSDT' ? 3800 : 50000;
            
            for (let i = 100; i >= 0; i--) {
                const time = now - i * 60 * 1000; // 1分钟间隔
                const open = basePrice + (Math.random() - 0.5) * 200;
                const volatility = Math.random() * 50;
                const high = open + volatility;
                const low = open - volatility;
                const close = low + Math.random() * (high - low);
                
                data.push({
                    time: time,
                    open: parseFloat(open.toFixed(2)),
                    high: parseFloat(high.toFixed(2)),
                    low: parseFloat(low.toFixed(2)),
                    close: parseFloat(close.toFixed(2)),
                    volume: Math.random() * 1000000
                });
            }
            
            return data;
        }
        
        // 初始化TradingView图表
        function initChart() {
            const widgetOptions = {
                symbol: currentSymbol,
                datafeed: customDatafeed,
                interval: '60', // TradingView格式的间隔
                container_id: 'tradingview_chart',
                library_path: '/charting_library/',
                locale: 'zh',
                disabled_features: ['use_localstorage_for_settings'],
                enabled_features: ['study_templates'],
                charts_storage_url: 'https://saveload.tradingview.com',
                charts_storage_api_version: '1.1',
                client_id: 'tradingview.com',
                user_id: 'public_user_id',
                fullscreen: false,
                autosize: true,
                theme: 'light',
                style: '1', // 蜡烛图
                timezone: 'Asia/Shanghai',
                debug: true,
                // 使用简化的CDN版本配置
                loading_screen: { backgroundColor: '#ffffff' },
                overrides: {
                    'volumePaneSize': 'medium',
                    'mainSeriesProperties.candleStyle.upColor': '#26a69a',
                    'mainSeriesProperties.candleStyle.downColor': '#ef5350',
                    'mainSeriesProperties.candleStyle.borderUpColor': '#26a69a', 
                    'mainSeriesProperties.candleStyle.borderDownColor': '#ef5350',
                    'mainSeriesProperties.candleStyle.wickUpColor': '#26a69a',
                    'mainSeriesProperties.candleStyle.wickDownColor': '#ef5350',
                }
            };
            
            console.log('初始化TradingView图表');
            
            try {
                // 由于可能没有完整的charting_library，我们使用简化的TradingView widget
                widget = new TradingView.widget({
                    width: '100%',
                    height: '100%',
                    symbol: `BINANCE:${currentSymbol}`,
                    interval: currentInterval === '1h' ? '60' : currentInterval,
                    timezone: 'Asia/Shanghai',
                    theme: 'light',
                    style: '1',
                    locale: 'zh',
                    toolbar_bg: '#f1f3f6',
                    enable_publishing: false,
                    allow_symbol_change: false,
                    container_id: 'tradingview_chart',
                    hide_side_toolbar: false,
                });
                
                hideLoading();
                updateStatus(true, '图表已加载');
                
            } catch (error) {
                console.error('TradingView图表初始化失败:', error);
                showError('图表加载失败，请检查网络连接');
                hideLoading();
            }
        }
        
        // 连接WebSocket
        function connectWebSocket() {
            try {
                const wsUrl = 'ws://localhost:8770';
                websocket = new WebSocket(wsUrl);
                
                websocket.onopen = () => {
                    console.log('WebSocket连接成功');
                    isConnected = true;
                    updateStatus(true, '已连接');
                    
                    // 订阅价格更新
                    websocket.send(JSON.stringify({
                        action: 'get_prices'
                    }));
                };
                
                websocket.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        handleWebSocketMessage(data);
                    } catch (error) {
                        console.error('解析WebSocket消息失败:', error);
                    }
                };
                
                websocket.onclose = () => {
                    console.log('WebSocket连接断开');
                    isConnected = false;
                    updateStatus(false, '连接断开');
                    
                    // 自动重连
                    setTimeout(connectWebSocket, 3000);
                };
                
                websocket.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                    updateStatus(false, '连接错误');
                };
                
            } catch (error) {
                console.error('WebSocket连接失败:', error);
                updateStatus(false, '连接失败');
            }
        }
        
        // 处理WebSocket消息
        function handleWebSocketMessage(data) {
            if (data.type === 'price_update') {
                updatePriceTicker(data.data);
            } else if (data.prices) {
                // 初始价格数据
                const symbolData = data.prices[currentSymbol];
                if (symbolData) {
                    updatePriceTicker(symbolData);
                }
            }
        }
        
        // 更新价格显示
        function updatePriceTicker(priceData) {
            if (priceData && priceData.s === currentSymbol) {
                const price = parseFloat(priceData.p);
                currentPrice.textContent = price.toFixed(2);
                
                // 这里可以添加更多价格信息的更新逻辑
                // 目前我们只有最新价格，可以扩展为包含24h高低价等
            }
        }
        
        // 更新连接状态
        function updateStatus(connected, text) {
            statusIndicator.className = `status-indicator ${connected ? 'connected' : ''}`;
            statusText.textContent = text;
        }
        
        // 显示错误消息
        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            setTimeout(() => {
                errorMessage.style.display = 'none';
            }, 5000);
        }
        
        // 显示/隐藏加载状态
        function showLoading() {
            loadingOverlay.style.display = 'flex';
        }
        
        function hideLoading() {
            loadingOverlay.style.display = 'none';
        }
        
        // 切换全屏
        function toggleFullscreen() {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen();
            } else {
                document.exitFullscreen();
            }
        }
        
        // 事件监听器
        symbolSelect.addEventListener('change', (e) => {
            currentSymbol = e.target.value;
            console.log('切换交易对到:', currentSymbol);
            // 重新初始化图表
            if (widget) {
                // 这里需要根据实际的TradingView API来更新图表
                location.reload(); // 临时解决方案
            }
        });
        
        intervalSelect.addEventListener('change', (e) => {
            currentInterval = e.target.value;
            console.log('切换时间周期到:', currentInterval);
            // 重新初始化图表
            if (widget) {
                location.reload(); // 临时解决方案
            }
        });
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            console.log('页面加载完成，开始初始化...');
            
            showLoading();
            
            // 初始化图表
            setTimeout(() => {
                initChart();
            }, 1000);
            
            // 连接WebSocket
            connectWebSocket();
        });
        
        // 页面卸载时清理
        window.addEventListener('beforeunload', () => {
            if (websocket) {
                websocket.close();
            }
        });
    </script>
</body>
</html>
